package de.sabram.upb.specs.eee_tools.wizards;

import java.net.URI;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;


public class EEEProjectSupport {
    /**
     * For this marvelous project we need to:
     * - create the default Eclipse project
     *
     * @param projectName
     * @param location
     * @return
     */
    public static IProject createProject(String projectName, URI location) {
    	
        IProject project = createBaseProject(projectName, location);
        try {
			addNature(project);
		} catch (CoreException e) {
			e.printStackTrace();
		}
        return project;
    }

    private static void addNature(IProject project) throws CoreException {
		if(!project.hasNature("org.eclipse.xtext.ui.shared.xtextNature")){
			IProjectDescription description = project.getDescription();
			String [] prevNatures = description.getNatureIds();
			String[] newNatures = new String[prevNatures.length +1];
			System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
			newNatures[prevNatures.length] = "org.eclipse.xtext.ui.shared.xtextNature";
			description.setNatureIds(newNatures);
			IProgressMonitor monitor=null;
			project.setDescription(description, monitor);
		}
		
	}

	/**
     * Just do the basics: create a basic project.
     *
     * @param location
     * @param projectName
     */
    private static IProject createBaseProject(String projectName, URI location) {
        // it is acceptable to use the ResourcesPlugin class
        IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);

        if (!newProject.exists()) {
            URI projectLocation = location;
            IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
            if (location != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location)) {
                projectLocation = null;
            }

            desc.setLocationURI(projectLocation);
            try {
                newProject.create(desc, null);
                if (!newProject.isOpen()) {
                    newProject.open(null);
                }
            } catch (CoreException e) {
                e.printStackTrace();
            }
        }

        return newProject;
    }
    

}
